package com.school.controller.common;

import com.school.config.ProjectConfig;
import com.school.util.Result;
import com.school.util.ResultGenerator;
import com.school.util.ResultGenerrator;
import com.school.util.TeaShopUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class UploadController {
    @Resource
    private StandardServletMultipartResolver standardServletMultipartResolver=new StandardServletMultipartResolver();
    @RequestMapping("/upload/file")
    @ResponseBody
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws URISyntaxException,IOException {
        BufferedImage bufferImage = ImageIO.read(file.getInputStream());
        if (bufferImage == null) {
            return ResultGenerator.genFailResult("上传失败");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Random r = new Random();
        String newFileName = sdf.format(new Date()) + r.nextInt(100) + suffixName;
        File fileDirectory = new File(ProjectConfig.getFileUploadPath());
        File destFile = new File(ProjectConfig.getFileUploadPath()+ newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdirs()) {
                    throw new IOException("文件路径创建失败" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            Result resultSuccess = ResultGenerator.genSuccessResult();
            resultSuccess.setData("/upload1/" + newFileName);
            return resultSuccess;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("上传失败");
    }
    @RequestMapping("/upload/files")
    @ResponseBody
    public Result upload2(HttpServletRequest request) throws URISyntaxException, IOException{
        ArrayList<MultipartFile> multipartFiles = new ArrayList<>();
        if(standardServletMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multipartHttpServletRequest.getFileNames();
            int total = 0;
            while (iter.hasNext()) {
                total++;
                MultipartFile file = multipartHttpServletRequest.getFile(iter.next());
                BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                if (bufferedImage != null) {
                    multipartFiles.add(file);
                }
            }
        }
        if(multipartFiles.size()==0){
            return ResultGenerator.genFailResult("请上传文件");
        }
        if(multipartFiles.size() > 5){
            return ResultGenerator.genFailResult("最多上传5个文件");

        }
        List<String> fileNames = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            String fileName = multipartFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Random r=new Random();
            String newFileName = sdf.format(new Date()) + r.nextInt(100) + suffixName;
            File fileDirectory = new File(ProjectConfig.getFileUploadPath());
            File destFile = new File(ProjectConfig.getFileUploadPath() + newFileName);
            if(!fileDirectory.exists()){
                if(!fileDirectory.mkdir()){
                    throw new IOException("文件夹创建失败,路径为："+fileDirectory);
                }
            }
            multipartFile.transferTo(destFile);
            fileNames.add(TeaShopUtils.getHost(new URI(ProjectConfig.getServerUrl()))+"/upload1/"+newFileName);
        }
        Result resultSuccess= ResultGenerrator.genSuccessResult();
        resultSuccess.setData(fileNames);
        return resultSuccess;
    }
}